package org.example.printexercise;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ImportArticleActivity extends AppCompatActivity {

    private EditText articleNameEditText;
    private EditText articleContentEditText;
    private Button btnLongText, btnWechatDialog, btnErrorProne;
    private Button btnAddArticle, btnCancel, btnSave;
    private LinearLayout layoutArticleInput;
    private ListView articleListView;
    private TextView tvArticlesTitle;
    private ArticleAdapter articleAdapter;

    private List<Article> articles = new ArrayList<>();
    private ArticleMode currentMode = ArticleMode.LONG_TEXT; // 默认模式
    private static final String PREFS_NAME = "ArticlesPrefs";
    private static final String ARTICLES_KEY = "SavedArticles";
    private static final String ENABLED_ARTICLE_KEY_PREFIX = "EnabledArticle_";

    // 默认文章名称常量
    private static final String DEFAULT_WORK_ARTICLE = "工作默认对话";
    private static final String DEFAULT_STUDY_ARTICLE = "学习默认对话";
    private static final String DEFAULT_FAMILY_ARTICLE = "家庭默认对话";

    // 文章模式枚举
    public enum ArticleMode {
        LONG_TEXT(1, "长文本文章"),
        WECHAT_DIALOG(2, "微信对话"),
        ERROR_PRONE(3, "易错字练习");

        private final int modeId;
        private final String displayName;

        ArticleMode(int modeId, String displayName) {
            this.modeId = modeId;
            this.displayName = displayName;
        }

        public int getModeId() {
            return modeId;
        }

        @Override
        public String toString() {
            return displayName;
        }

        public static ArticleMode fromId(int id) {
            for (ArticleMode mode : values()) {
                if (mode.getModeId() == id) {
                    return mode;
                }
            }
            return LONG_TEXT; // 默认返回长文本模式
        }
    }

    // 文章数据类
    public static class Article {
        private String name;
        private String content;
        private ArticleMode mode;
        private boolean enabled;
        private boolean isDefault = false; // 标记是否为默认文章

        public Article(String name, String content, ArticleMode mode) {
            this.name = name;
            this.content = content;
            this.mode = mode;
            this.enabled = false;
        }

        // 构造函数用于创建默认文章
        public Article(String name, String content, ArticleMode mode, boolean isDefault) {
            this.name = name;
            this.content = content;
            this.mode = mode;
            this.enabled = false;
            this.isDefault = isDefault;
        }

        // Getters and Setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }

        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }

        public ArticleMode getMode() { return mode; }
        public void setMode(ArticleMode mode) { this.mode = mode; }

        public boolean isEnabled() { return enabled; }
        public void setEnabled(boolean enabled) { this.enabled = enabled; }

        public boolean isDefault() { return isDefault; }
        public void setDefault(boolean aDefault) { isDefault = aDefault; }

        @Override
        public String toString() {
            return name + " (" + mode.toString() + ")";
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import_article);

        initViews();
        loadArticles();
        setupListeners();
        switchMode(ArticleMode.LONG_TEXT); // 默认显示长文本模式
    }

    private void initViews() {
        articleNameEditText = findViewById(R.id.articleNameEditText);
        articleContentEditText = findViewById(R.id.articleContentEditText);
        btnLongText = findViewById(R.id.btn_long_text);
        btnWechatDialog = findViewById(R.id.btn_wechat_dialog);
        btnErrorProne = findViewById(R.id.btn_error_prone);
        btnAddArticle = findViewById(R.id.btn_add_article);
        btnCancel = findViewById(R.id.btn_cancel);
        btnSave = findViewById(R.id.btn_save);
        layoutArticleInput = findViewById(R.id.layout_article_input);
        articleListView = findViewById(R.id.articleListView);
        tvArticlesTitle = findViewById(R.id.tv_articles_title);

        // 设置文章列表适配器
        articleAdapter = new ArticleAdapter(this, new ArrayList<>());
        articleListView.setAdapter(articleAdapter);
    }

    private void setupListeners() {
        // 模式切换按钮
        btnLongText.setOnClickListener(v -> switchMode(ArticleMode.LONG_TEXT));
        btnWechatDialog.setOnClickListener(v -> switchMode(ArticleMode.WECHAT_DIALOG));
        btnErrorProne.setOnClickListener(v -> switchMode(ArticleMode.ERROR_PRONE));

        // 新增文章按钮
        btnAddArticle.setOnClickListener(v -> showArticleInput(true, null));

        // 取消和保存按钮
        btnCancel.setOnClickListener(v -> showArticleInput(false, null));
        btnSave.setOnClickListener(v -> saveArticle());

        // 文章列表点击事件
        articleListView.setOnItemClickListener((parent, view, position, id) -> {
            enableArticle(position);
        });

        // 文章列表长按事件
        articleListView.setOnItemLongClickListener((parent, view, position, id) -> {
            showArticleOptions(position);
            return true;
        });

        articleContentEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateSaveButtonState();
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void switchMode(ArticleMode mode) {
        currentMode = mode;

        // 更新按钮状态
        updateModeButtonStates();

        // 更新标题
        tvArticlesTitle.setText(mode.toString());

        // 加载对应模式的文章
        loadArticlesForCurrentMode();

        // 隐藏文章输入区域
        showArticleInput(false, null);
    }

    private void updateModeButtonStates() {
        // 重置所有按钮为灰色
        btnLongText.setBackgroundTintList(getColorStateList(android.R.color.darker_gray));
        btnWechatDialog.setBackgroundTintList(getColorStateList(android.R.color.darker_gray));
        btnErrorProne.setBackgroundTintList(getColorStateList(android.R.color.darker_gray));

        // 设置当前模式按钮为蓝色
        switch (currentMode) {
            case LONG_TEXT:
                btnLongText.setBackgroundTintList(getColorStateList(android.R.color.holo_blue_dark));
                break;
            case WECHAT_DIALOG:
                btnWechatDialog.setBackgroundTintList(getColorStateList(android.R.color.holo_blue_dark));
                break;
            case ERROR_PRONE:
                btnErrorProne.setBackgroundTintList(getColorStateList(android.R.color.holo_blue_dark));
                break;
        }
    }

    private void loadArticlesForCurrentMode() {
        List<Article> filteredArticles = new ArrayList<>();

        // 如果是微信对话模式，确保默认选项已加载
        if (currentMode == ArticleMode.WECHAT_DIALOG) {
            ensureDefaultWeChatArticles();
        }

        for (Article article : articles) {
            if (article.getMode() == currentMode) {
                filteredArticles.add(article);
            }
        }
        articleAdapter.updateArticles(filteredArticles);
    }

    // 确保微信对话默认选项已加载
    private void ensureDefaultWeChatArticles() {
        boolean hasWorkDefault = false;
        boolean hasStudyDefault = false;
        boolean hasFamilyDefault = false;

        // 检查是否已经存在默认文章
        for (Article article : articles) {
            if (article.getMode() == ArticleMode.WECHAT_DIALOG && article.isDefault()) {
                switch (article.getName()) {
                    case DEFAULT_WORK_ARTICLE:
                        hasWorkDefault = true;
                        break;
                    case DEFAULT_STUDY_ARTICLE:
                        hasStudyDefault = true;
                        break;
                    case DEFAULT_FAMILY_ARTICLE:
                        hasFamilyDefault = true;
                        break;
                }
            }
        }

        // 如果不存在默认文章，则加载它们
        if (!hasWorkDefault || !hasStudyDefault || !hasFamilyDefault) {
            loadDefaultWeChatArticles();
        }
    }

    // 从JSON文件加载默认微信文章
    private void loadDefaultWeChatArticles() {
        try {
            // 读取 raw 资源文件
            InputStream inputStream = getResources().openRawResource(R.raw.wechatdata);
            Scanner scanner = new Scanner(inputStream);
            StringBuilder stringBuilder = new StringBuilder();
            while (scanner.hasNextLine()) {
                stringBuilder.append(scanner.nextLine());
            }
            String jsonContent = stringBuilder.toString();
            scanner.close();

            // 解析 JSON
            JSONObject jsonObject = new JSONObject(jsonContent);

            // 检查是否已有默认文章，避免重复添加
            boolean workExists = false, studyExists = false, familyExists = false;
            for (Article article : articles) {
                if (article.getMode() == ArticleMode.WECHAT_DIALOG && article.isDefault()) {
                    if (DEFAULT_WORK_ARTICLE.equals(article.getName())) workExists = true;
                    if (DEFAULT_STUDY_ARTICLE.equals(article.getName())) studyExists = true;
                    if (DEFAULT_FAMILY_ARTICLE.equals(article.getName())) familyExists = true;
                }
            }

            // 添加工作默认对话
            if (!workExists && jsonObject.has("work") && jsonObject.getJSONArray("work").length() > 0) {
                JSONArray workArray = jsonObject.getJSONArray("work");
                StringBuilder workContent = new StringBuilder();
                for (int i = 0; i < Math.min(workArray.length(), 10); i++) { // 取前10条
                    if (i > 0) workContent.append("\n");
                    workContent.append(workArray.getString(i));
                }
                Article workArticle = new Article(DEFAULT_WORK_ARTICLE, workContent.toString(), ArticleMode.WECHAT_DIALOG, true);
                articles.add(workArticle);
            }

            // 添加学习默认对话
            if (!studyExists && jsonObject.has("study") && jsonObject.getJSONArray("study").length() > 0) {
                JSONArray studyArray = jsonObject.getJSONArray("study");
                StringBuilder studyContent = new StringBuilder();
                for (int i = 0; i < studyArray.length(); i++) {
                    if (i > 0) studyContent.append("\n");
                    studyContent.append(studyArray.getString(i));
                }
                Article studyArticle = new Article(DEFAULT_STUDY_ARTICLE, studyContent.toString(), ArticleMode.WECHAT_DIALOG, true);
                articles.add(studyArticle);
            }

            // 添加家庭默认对话
            if (!familyExists && jsonObject.has("family") && jsonObject.getJSONArray("family").length() > 0) {
                JSONArray familyArray = jsonObject.getJSONArray("family");
                StringBuilder familyContent = new StringBuilder();
                for (int i = 0; i < familyArray.length(); i++) {
                    if (i > 0) familyContent.append("\n");
                    familyContent.append(familyArray.getString(i));
                }
                Article familyArticle = new Article(DEFAULT_FAMILY_ARTICLE, familyContent.toString(), ArticleMode.WECHAT_DIALOG, true);
                articles.add(familyArticle);
            }

            // 保存更新后的文章列表
            saveArticles();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载默认微信对话失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void showArticleInput(boolean show, Article articleToEdit) {
        if (show) {
            layoutArticleInput.setVisibility(View.VISIBLE);
            if (articleToEdit != null) {
                // 编辑模式
                articleNameEditText.setText(articleToEdit.getName());
                articleContentEditText.setText(articleToEdit.getContent());
                btnSave.setTag(articleToEdit); // 保存正在编辑的文章引用
            } else {
                // 新增模式
                articleNameEditText.setText("");
                articleContentEditText.setText("");
                btnSave.setTag(null);
            }
        } else {
            layoutArticleInput.setVisibility(View.GONE);
            btnSave.setTag(null);
        }
    }

    private void updateSaveButtonState() {
        String name = articleNameEditText.getText().toString().trim();
        String content = articleContentEditText.getText().toString().trim();
        btnSave.setEnabled(!name.isEmpty() && !content.isEmpty());
    }

    private void saveArticle() {
        String name = articleNameEditText.getText().toString().trim();
        String content = articleContentEditText.getText().toString().trim();

        if (name.isEmpty() || content.isEmpty()) {
            Toast.makeText(this, "请填写文章名称和内容", Toast.LENGTH_SHORT).show();
            return;
        }

        Article existingArticle = (Article) btnSave.getTag();
        if (existingArticle != null) {
            // 编辑模式
            existingArticle.setName(name);
            existingArticle.setContent(content);
        } else {
            // 新增模式
            Article article = new Article(name, content, currentMode);
            articles.add(article);
        }
        saveArticles();

        // 刷新当前模式的文章列表
        loadArticlesForCurrentMode();

        // 隐藏输入区域
        showArticleInput(false, null);

        Toast.makeText(this, "文章保存成功", Toast.LENGTH_SHORT).show();
    }

    private void enableArticle(int position) {
        List<Article> currentModeArticles = articleAdapter.getArticles();
        if (position >= 0 && position < currentModeArticles.size()) {
            Article article = currentModeArticles.get(position);

            // 取消同模式下的其他文章的启用状态
            for (Article a : articles) {
                if (a.getMode() == currentMode) {
                    a.setEnabled(false);
                }
            }

            // 启用当前文章
            article.setEnabled(true);
            saveArticles();

            // 刷新列表
            loadArticlesForCurrentMode();

            Toast.makeText(this, "已启用文章: " + article.getName(), Toast.LENGTH_SHORT).show();
        }
    }

    private void showArticleOptions(int position) {
        List<Article> currentModeArticles = articleAdapter.getArticles();
        if (position >= 0 && position < currentModeArticles.size()) {
            Article article = currentModeArticles.get(position);

            // 对于默认文章，只提供查看选项
            if (article.isDefault()) {
                String[] options = {"查看"};

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("默认文章")
                        .setItems(options, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                viewArticle(article);
                            }
                        })
                        .show();
            } else {
                // 对于用户自定义文章，提供完整的操作选项
                String[] options = {"查看", "编辑", "删除"};

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("选择操作")
                        .setItems(options, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0: // 查看
                                        viewArticle(article);
                                        break;
                                    case 1: // 编辑
                                        editArticle(article);
                                        break;
                                    case 2: // 删除
                                        confirmDeleteArticle(article);
                                        break;
                                }
                            }
                        })
                        .show();
            }
        }
    }

    private void viewArticle(Article article) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(article.getName())
                .setMessage(article.getContent())
                .setPositiveButton("确定", null)
                .show();
    }

    private void editArticle(Article article) {
        showArticleInput(true, article);
    }

    private void confirmDeleteArticle(Article article) {
        // 确保不能删除默认文章
        if (article.isDefault()) {
            Toast.makeText(this, "默认文章无法删除", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认删除")
                .setMessage("确定要删除文章 \"" + article.getName() + "\" 吗？")
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteArticle(article);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteArticle(Article article) {
        articles.remove(article);
        saveArticles();
        loadArticlesForCurrentMode();
        Toast.makeText(this, "文章已删除", Toast.LENGTH_SHORT).show();
    }

    private void saveArticles() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(articles);
        editor.putString(ARTICLES_KEY, json);
        editor.apply();
    }

    private void loadArticles() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String json = prefs.getString(ARTICLES_KEY, "");

        if (!json.isEmpty()) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Article>>(){}.getType();
            articles = gson.fromJson(json, type);
            if (articles == null) {
                articles = new ArrayList<>();
            }
        } else {
            articles = new ArrayList<>();
        }
    }

    // 获取指定模式下启用的文章
    public static String getEnabledArticleContent(Context context, int modeId) {
        ArticleMode mode = ArticleMode.fromId(modeId);
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String json = prefs.getString(ARTICLES_KEY, "");

        if (!json.isEmpty()) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Article>>(){}.getType();
            List<Article> allArticles = gson.fromJson(json, type);

            if (allArticles != null) {
                for (Article article : allArticles) {
                    if (article.getMode() == mode && article.isEnabled()) {
                        return article.getContent();
                    }
                }
            }
        }

        return "当前模式未创建文章，请前往导入文章页面导入文章";
    }

    // 文章列表适配器
    private class ArticleAdapter extends BaseAdapter {
        private Context context;
        private List<Article> articles;
        private LayoutInflater inflater;

        public ArticleAdapter(Context context, List<Article> articles) {
            this.context = context;
            this.articles = articles != null ? articles : new ArrayList<>();
            this.inflater = LayoutInflater.from(context);
        }

        public void updateArticles(List<Article> newArticles) {
            this.articles = newArticles != null ? newArticles : new ArrayList<>();
            notifyDataSetChanged();
        }

        public List<Article> getArticles() {
            return articles;
        }

        @Override
        public int getCount() {
            return articles.size();
        }

        @Override
        public Object getItem(int position) {
            return articles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(android.R.layout.simple_list_item_2, parent, false);
            }

            Article article = articles.get(position);
            TextView text1 = convertView.findViewById(android.R.id.text1);
            TextView text2 = convertView.findViewById(android.R.id.text2);

            // 如果是默认文章，在名称后添加标识
            if (article.isDefault()) {
                text1.setText(article.getName() + " (默认)");
            } else {
                text1.setText(article.getName());
            }

            text2.setText(article.getMode().toString());

            // 根据启用状态设置颜色
            if (article.isEnabled()) {
                text1.setTextColor(0xFF4CAF50); // 绿色
                text2.setTextColor(0xFF4CAF50); // 绿色
            } else {
                text1.setTextColor(0xFF000000); // 黑色
                text2.setTextColor(0xFF666666); // 灰色
            }

            return convertView;
        }
    }
}
